import React, { useState, useEffect } from "react";
import { Card, Popup, Toast, Sidebar, Image, Dialog } from "react-vant";
import { Search } from "@react-vant/icons";
import { useNavigate, useLocation } from "react-router-dom";
import RBACManager from "../../utils/rbacManager";
import axios from "axios";

import "./TopNav.css";

// 有料LOGO和搜索、通知、用户头像封装公共的组件
const TopNav = () => {
  const [visible, setVisible] = useState(false);
  // 添加表单数据状态
  const [supportForm, setSupportForm] = useState({
    subject: "技术难点",
    description: "",
  });
  const [state, setState] = useState("");
  const [active, setActive] = useState(0);
  const navigate = useNavigate();
  const location = useLocation(); // Get the current location
  const [user, setUser] = useState([]);
  const [supportVisible, setSupportVisible] = useState(false);

  const [showUserMenu, setShowUserMenu] = useState(false);
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    // 获取用户数据
    const authData = RBACManager.getUserPermissions();
    setUserData(authData);
  }, []);

  const data = async () => {
    const res = await axios.get("http://192.168.0.154:3000/cats");
    setUser(res.data);
  };

  // 处理表单输入变化
  const handleSupportFormChange = (field, value) => {
    setSupportForm((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  // 发送支持请求
  const handleSupportSubmit = async () => {
    try {
      await axios.post("http://192.168.0.154:3000/my/online", supportForm);
      Toast.success("请求已发送");
      setSupportVisible(false);
      // 重置表单
      setSupportForm({
        subject: "技术难点",
        description: "",
      });
    } catch (error) {
      Toast.fail("发送失败，请重试");
      console.error("Support request error:", error);
    }
  };

  useEffect(() => {
    data();
  }, []);

  const titleList = [
    { id: 0, title: "仪表盘", path: "/admin-dashboard", icon: <Search /> },
    { id: 1, title: "项目", path: "/project", icon: <Search /> },
    { id: 2, title: "日历", path: "/calendar", icon: <Search /> },
    { id: 3, title: "假期", path: "/vacation", icon: <Search /> },
    { id: 4, title: "员工", path: "/staff", icon: <Search /> },
    { id: 5, title: "消息", path: "/message", icon: <Search /> },
    { id: 6, title: "门户网站", path: "/website", icon: <Search /> },
    { id: 7, title: "在线支持", icon: <Search /> },
    { id: 8, title: "退出登录", icon: <Search /> },
  ];
  // Update the active state based on the current route
  useEffect(() => {
    const currentPath = location.pathname;
    const currentIndex = titleList.findIndex(
      (item) => item.path === currentPath
    );
    if (currentIndex !== -1) {
      setActive(currentIndex);
    } else {
      setActive(0); // Default to the first item if no match found
    }
  }, [location, titleList]);

  const handleSidebarChange = (v) => {
    setActive(v);
    Toast.info(`${titleList[v].title}`);
    // 根据点击的标签进行路由跳转
    navigate(titleList[v].path);
    if (titleList[v].title === "在线支持") {
      setSupportVisible(true);
    } else if (titleList[v].title === "退出登录") {
      Dialog.confirm({
        title: "退出确认",
        message: "确定要退出登录吗？",
        confirmButtonText: "确定退出",
        cancelButtonText: "取消",
        confirmButtonColor: "#ff4d4f",
      })
        .then(() => {
          // 清除权限数据
          RBACManager.clearPermissions();

          // 清除其他相关的本地存储
          localStorage.removeItem("registerStep1");
          localStorage.removeItem("currentUser");
          localStorage.removeItem("teamMembers");
          localStorage.removeItem("registerStep3");
          localStorage.removeItem("registerStep2");
          localStorage.removeItem("rememberedEmail");
          localStorage.removeItem("authData");
          localStorage.removeItem("isLoggedIn");

          // 显示退出成功提示
          Toast.success("已成功退出登录");

          // 延迟跳转到登录页
          setTimeout(() => {
            navigate("/login");
          }, 1000);
        })
        .catch(() => {
          // 用户取消退出
        });
    } else {
      setActive(v);
      Toast.info(`${titleList[v].title}`);
      navigate(titleList[v].path);
    }
    onClose();
  };

  const onClose = () => setState("");

  return (
    <div>
      <Card
        round
        border
        className="TopCard"
        style={{
          width: "90%",
          height: "0px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          height: "70px",
          backgroundColor: "#f8fefb",
          margin: "0 auto",
          marginTop: "20px",
          borderRadius: "10px",
        }}
      >
        <div style={{ marginLeft: "10px" }}>
          <img
            src="./Website/TopNav/youliaoLogo.png"
            style={{ width: "50px" }}
            onClick={() => setState("left")}
          />
        </div>
        <Popup
          visible={state === "left"}
          style={{
            width: "30%",
            height: "80%",
            borderRadius: "10px",
            marginLeft: "10px",
            marginTop: "40px",
          }}
          position="left"
          onClose={onClose}
        >
          <Sidebar
            sideStyle={{ width: "150px" }}
            value={active}
            onChange={handleSidebarChange}
          >
            {titleList.map((item) => (
              <Sidebar.Item key={item.id} title={item.title}></Sidebar.Item>
            ))}
          </Sidebar>
        </Popup>
        <div
          style={{
            width: "120px",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginRight: "10px",
          }}
        >
          <Search style={{ width: "25px", height: "25px" }} />
          <img
            src="./Website/TopNav/notifications.png"
            style={{ width: "25px", height: "25px" }}
            onClick={() => {
              setVisible(true);
            }}
          />
          <img
            src="./Website/TopNav/user.png"
            style={{ width: "25px", height: "25px" }}
          />
        </div>
        <Popup
          visible={visible}
          onClose={() => setVisible(false)}
          closeable
          style={{ borderRadius: "10px" }}
        >
          <Card round style={{ width: "340px", height: "576px" }}>
            <Card.Header style={{ marginTop: "10px" }}>通知</Card.Header>
            <Card.Body className="popup-body">
              {" "}
              {/* 使用新的CSS类 */}
              {user.map((item) => {
                return (
                  <div
                    key={item.id}
                    style={{
                      width: "100%",
                      height: "100px",
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        marginTop: "6%",
                      }}
                    >
                      <Image width={44} height={44} src="/demo_1.jpg" round />
                      <div style={{ width: "80%" }}>{item.neirong}</div>
                    </div>
                    <div style={{ marginLeft: "20%" }}>{item.age}</div>
                  </div>
                );
              })}
            </Card.Body>
          </Card>
        </Popup>
      </Card>
      <Popup
        visible={supportVisible}
        onClose={() => setSupportVisible(false)}
        closeable
        style={{ borderRadius: "10px" }}
      >
        <Card round style={{ width: "340px", height: "400px" }}>
          <Card.Header>需要一些帮助？</Card.Header>
          <Card.Body>
            <div style={{ padding: "16px" }}>
              <p>请描述您的问题，我们的专家将在24小时内答复您。</p>
              <div style={{ marginTop: "16px" }}>
                <div>问题主题</div>
                <select
                  value={supportForm.subject}
                  onChange={(e) =>
                    handleSupportFormChange("subject", e.target.value)
                  }
                  style={{
                    width: "100%",
                    padding: "8px",
                    marginTop: "8px",
                    borderRadius: "4px",
                    border: "1px solid #ddd",
                  }}
                >
                  <option value="技术难点">技术难点</option>
                  <option value="功能建议">功能建议</option>
                  <option value="使用问题">使用问题</option>
                  <option value="其他">其他</option>
                  {/* 添加更多选项 */}
                </select>
              </div>
              <div style={{ marginTop: "16px" }}>
                <div>问题描述</div>
                <textarea
                  value={supportForm.description}
                  onChange={(e) =>
                    handleSupportFormChange("description", e.target.value)
                  }
                  placeholder="请添加问题的一些描述"
                  style={{
                    width: "95%",
                    height: "80px",
                    padding: "8px",
                    marginTop: "8px",
                    borderRadius: "4px",
                    border: "1px solid #ddd",
                    resize: "none",
                  }}
                />
              </div>
              <button
                onClick={handleSupportSubmit}
                style={{
                  width: "100%",
                  padding: "12px",
                  marginTop: "16px",
                  backgroundColor: "#3f8cff",
                  color: "white",
                  border: "none",
                  borderRadius: "15px",
                  cursor: "pointer",
                }}
              >
                发送请求
              </button>
            </div>
          </Card.Body>
        </Card>
      </Popup>
    </div>
  );
};

export default TopNav;
